<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "meta".
 *
 * @property string $id
 * @property string $title
 * @property string $keywords
 * @property string $description
 * @property string $type
 * @property string $pk
 */
class Meta extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'meta';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['type', 'pk'], 'required'],
            [['pk'], 'integer'],
            [['title', 'keywords', 'description'], 'string', 'max' => 128],
            [['type'], 'string', 'max' => 50],
            [['type', 'pk'], 'unique', 'targetAttribute' => ['type', 'pk'], 'message' => 'The combination of 类型：如catalog,post and 类型id has already been taken.'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
            'keywords' => 'Keywords',
            'description' => 'Description',
            'type' => '类型：如catalog,post',
            'pk' => '类型id',
        ];
    }

    /**
     * 返回Meta对象
     * @param $type
     * @param $pk
     * @return array|Meta|null|\yii\db\ActiveRecord
     */
    public static function get($type, $pk)
    {
        $model = Meta::find()->where("type=:type and pk=:pk", [":type" => $type, ":pk" => $pk])->one();
        if (!$model) {
            $model = new Meta();
        }
        return $model;
    }

    /**
     * 保存
     * @param $type string 类型
     * @param $pk int 类型id
     */
    public static function log($type, $pk)
    {

        $model = Meta::get($type, $pk);
        $model->load(Yii::$app->request->post());
        if ($model->title || $model->keywords || $model->description) {
            $model->type = $type;
            $model->pk = $pk;
            $model->save();
        }
    }

    public static function del($type, $pk)
    {
        Meta::get($type, $pk)->delete();
    }
}
